"use strict";

const elasticsearch = require("@elastic/elasticsearch");
const createOneClient = (config, app) => {
  let tempClient = { sql: {} };
  let client = new elasticsearch.Client(config);
  // 查询
  tempClient.search = async (query) => {
    try {
      let result = await client.search(query);
      let temp = {
        count: result.body.hits.total.value,
        rows: result.body.hits.hits.map((item) => {
          if (item.highlight) {
            for (let key in item.highlight) {
              item.highlight[key] = item.highlight[key][0];
            }
          }
          return { ...item._source, ...item.highlight };
        }),
      };
      if (result.body.aggregations) {
        temp.aggs = result.body.aggregations;
      }
      return temp;
    } catch (e) {
      throw e;
    }
  };
  // 统计
  tempClient.count = async (query) => {
    try {
      let result = await client.count(query);
      return { count: result.body.count };
    } catch (e) {
      throw e;
    }
  };
  // 获取详细
  tempClient.get = async (query) => {
    try {
      const res = await client.get(query);
      return res.body._source;
    } catch (e) {
      throw e;
    }
  };
  // 通过SQL查询
  tempClient.sql.query = async (query) => {
    try {
      const { body } = await client.sql.query(query);
      const data = body.rows.map((row) => {
        const obj = {};
        for (let i = 0; i < row.length; i++) {
          obj[body.columns[i].name] = row[i];
        }
        return obj;
      });
      return data;
    } catch (e) {
      throw e;
    }
  };
  return tempClient;
};

module.exports = (app) => {
  // 注意这里很关键，第一个参数“zzes”是挂到app上的字段，可以通过”app.zzes“访问到es的实例
  app.addSingleton("zzes", createOneClient);
};
